// pages/module/order/commitOrder/commitOrder.js
import { orderSave, orderPay, orderUpdate,wxPay,gift_save } from '../../../utils/imapi'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    networkType: 1,
    show: 1,
    showMoney: 0,
    psd_id: '1',
    is_setAddress: 0,
    buy_user_address: '',
    buy_user_mobile: '',
    buy_user_name: '',
    address_id: '',
    data: app.globalData.cur_product_buy,
    showMask: 0,
    qustion: 0,
    agreementMask: 0,
    agreement: '',
    switchValue: 0,
    currentDay: 0,
    id: 0,
    clickAgreement: 0,
    day: 0,
    clickPay: 1,
    order_id: 0,
    part_count: 0,
	part_count1:0,
    show_pay_total: 0,
    show_save_total: 0,
    fromOptions: {},
    order_remark:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
     var that = this;
     console.log(app.globalData.cur_product_buy)
    const price = app.globalData.cur_product_buy.price;
    const zk_price = app.globalData.cur_product_buy.zk_price;
    const count = app.globalData.cur_product_buy.count1;
	const count1 = app.globalData.cur_product_buy.count2;
    this.setData({
      data: app.globalData.cur_product_buy,
      part: app.globalData.cur_product_buy.part.map(item => (item = `${item}`)).join('   '),
      part_count: count,
	  part_count1: count1,
      show_pay_total: zk_price * count * count1 ,
      show_save_total: (price - zk_price) * count * count1,
      fromOptions: options
    })
  },
  minus() {
    const count = (this.data.part_count1 - 1) == 0 ? 1 : (this.data.part_count1 - 1);
    this.setData({
      part_count1: count,
      show_pay_total: this.data.data.zk_price * count * this.data.part_count,
      show_save_total: (this.data.data.price - this.data.data.zk_price) * count * this.data.part_count,
    })
  },
  add() {
    const count = (this.data.part_count1 + 1) > this.data.data.amount ? this.data.data.amount : (this.data.part_count1 + 1)
    this.setData({
      part_count1: count,
      show_pay_total: this.data.data.zk_price * count * this.data.part_count,
      show_save_total: (this.data.data.price - this.data.data.zk_price) * count * this.data.part_count,
    })
  },
  // 添加地址
  addAdress: function () {
    var that = this;
    var data = {};



    
    wx.chooseAddress({
      success: function (res) {
        data.userName = res.userName;
        data.postalCode = res.postalCode;
        data.provinceName = res.provinceName;
        data.cityName = res.cityName;
        data.countyName = res.countyName;
        data.detailInfo = res.detailInfo;
        data.nationalCode = res.nationalCode;
        data.telNumber = res.telNumber;
        that.setData({
          is_setAddress: 1,
          buy_user_address: res.provinceName + res.cityName + res.countyName + res.detailInfo,
          buy_user_name: res.userName,
          buy_user_mobile: res.telNumber,
          address: data
        })
      },
      fail: function (err) {

      }
    })
  },

  showMask(e) {
    var id = e.currentTarget.dataset.id;
    this.setData({
      showMask: 1,
      qustion: id
    })
  },
  // 用户协议
  agreement() {
    var that = this;
    if (that.data.agreement) {
      that.setData({
        agreementMask: 1,
      })
    } else {

    }
  },
  // 关闭弹窗
  closeMask() {
    this.setData({
      showMask: 0,
      agreementMask: 0,
    })
  },
  // 选择按钮
  switchChange(e) {
    // console.log(e);
    var val = e.detail.value ? '1' : '0'
    this.setData({
      switchValue: val
    })
  },

  // 勾选协议
  clickAgreement() {
    this.setData({
      clickAgreement: !this.data.clickAgreement
    })
  },
  // 订单支付
  async orderPay() {
    var that = this;
	wx.showLoading({ title: '正在下单' });
	let date={
		pay:this.data.show_pay_total
	}
	app.globalData.order_info = date
	const data = {
	  price:this.data.show_pay_total,
	  in_out: 'I',
	  fin_type: 'GW',
	  //ref_order_no: orderInfo.order_no.toString(),
	}
	
	const res = await orderPay(data);
	console.log(res);
	wx.hideLoading();
	if (res.code === 0) {
	  const data = {
	    timeStamp: res.data.timestamp,
	    nonceStr: res.data.nonceStr,
	    package: res.data.package,
	    signType: res.data.signType,
	    paySign: res.data.paySign,
	    success: () => {
			const item={
					      item_id:this.data.data.item_id,  //id商品
					      mchs_id:this.data.data.shop_id,  //商品id
						  spec1:this.data.data.part[0],
						  spec2:this.data.data.part[1],
						  spec_id:this.data.fromOptions.spec_id,  //规格
						  buy_amt:this.data.data.count1,
						  price:this.data.data.price,
						  buy_price:this.data.data.zk_price,
						  goods_title:this.data.data.title, //商品标题
						  pay_order_no:res.data.prePayId, 
						  order_no:res.data.order_no, //内部单号
						  gift_num:this.data.data.count2, //劵数
			}
			gift_save(item);
	      //console.log(red);
	      wx.redirectTo({
	        url: `/packageTab/pages/commitOrder/paySuccess/paySuccess?room_id=${this.data.fromOptions.room_id}&custom_params=${this.data.fromOptions.custom_params}&show_pay_total=${this.data.show_pay_total}`
	      })
	      //orderUpdate({ order_id: orderInfo.order_no.toString() })
	    },
	    fail: (err) => {
	      console.log('失败', err)
	      wx.navigateTo({
	        url:`/pages/module/orderDetail/orderDetail?id=${orderInfo.order_no.toString()}`
	      })
	    }
	  }
	  
	  wx.requestPayment(data)
	}
  },

  async wxPay(that) {
    wx.showLoading({ title: '正在下单' })
    const sub_pid = this.data.fromOptions.sub_pid;
    console.log(this.data.address)
    const address = this.data.address;
    let data = {
      item_id: this.data.data.item_id,
      // item_id: 4,
      mchs_id: this.data.data.shop_id,
      // mchs_id: '1285496604144435201',
      spec1: this.data.data.part[0] || '',
      // spec1: 'L',
      spec2: this.data.data.part[1] || '',
      // spec2: '黄色',
      goods_amt: this.data.part_count,
      sub_pid: sub_pid,
      name: address.userName,
      phone: address.telNumber,
      provice: address.provinceName,
      city: address.cityName,
      counties: address.countyName,
      detailinfo: address.detailInfo,
      postal_code: address.postalCode
    }
    app.globalData.order_info = data;
    app.globalData.order_info.address = this.data.buy_user_address;
    const res = await orderSave(data);
    if (res.data)
      await this.pay(res.data);
  },
  async pay(orderInfo) {
    const data = {
      // price: orderInfo.price,
      price: this.data.show_pay_total,
      in_out: 'I',
      fin_type: 'GW',
      //ref_order_no: orderInfo.order_no.toString(),
    }
    app.globalData.order_info.pay = this.data.show_pay_total;
    const res = await orderPay(data);
    wx.hideLoading();
    if (res.code === 0) {
      const data = {
        timeStamp: res.data.timestamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: () => {
          console.log('成功')
          wx.navigateTo({
            url: `/pages/module/commitOrder/paySuccess/paySuccess?room_id=${this.data.fromOptions.room_id}&custom_params=${this.data.fromOptions.custom_params}`
          })
          orderUpdate({ order_id: orderInfo.order_no.toString() })
        },
        fail: (err) => {
          console.log('失败', err)
          wx.navigateTo({
            url:`/pages/module/orderDetail/orderDetail?id=${orderInfo.order_no.toString()}`
          })
        }
      }
      wx.requestPayment(data)
    }
  },
  // 存储formid
  sendFormId(e) {
    var that = this;
    var form_id = e.detail.formId;
    var url = 'api/log/emptynull';
    var data = {
      formid: form_id
    };
    req.get(that, url, data, (res) => { })
  },
  inputEditHandler(e){
    this.setData({
      order_remark: e.detail.value
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})